axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net';

const tb = document.querySelector('#tb');
const form = document.querySelector('#bookForm');
const sx = document.querySelector('.sx');

// 获取数据
async function render(data) {
  const { data: res } = await axios.get('/api/getbooks?' + data );
  console.log(res);
  tb.innerHTML = res.data
    .map((item) => {
      return ` <tr>
    <td>${item.id}</td>
    <td>${item.bookname}</td>
    <td>${item.author}</td>
    <td>${item.publisher}</td>
    <td><a href="#" data-id="${item.id}">删除</a></td>
  </tr>`;
    })
    .join('');
}
render();

//添加数据
form.addEventListener('submit', async function (e) {
  e.preventDefault();
  const data = serialize(form, { hash: true });
  const { data: res } = await axios.post('/api/addbook', data);

  alert(res.msg);
  if (!(res.status === 201)) return;
  render();

  form.reset();
});

// 删除数据
tb.addEventListener('click', async function (e) {
  if (e.target.tagName === 'A') {
    const id = e.target.dataset.id;
    const { data: res } = await axios.get('/api/delbook?id=' + id);
    render();
  }
});

//筛选数据
sx.addEventListener('click', async function () {
  const news = serialize(form, { hash: false });
  if(!news) return alert('内容不能为空') 
  render(news)
});
